import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:family_app/src/features/auth/models/user_model.dart';
import 'package:family_app/src/features/auth/services/auth_service.dart';

/// u767bu5f55u72b6u6001u63d0u4f9bu8005
final authStateProvider = StateNotifierProvider<AuthNotifier, AuthState>((ref) {
  final authService = ref.watch(authServiceProvider);
  return AuthNotifier(authService);
});

/// u9a8cu8bc1u7801u53d1u9001u72b6u6001u63d0u4f9bu8005
final sendCodeStateProvider = StateProvider.autoDispose<SendCodeState>((ref) {
  return const SendCodeState.initial();
});

/// u6ed1u5757u9a8cu8bc1u7801u72b6u6001u63d0u4f9bu8005
final captchaStateProvider = StateProvider.autoDispose<CaptchaState>((ref) {
  return const CaptchaState.initial();
});

/// u767bu5f55u65b9u5f0fu63d0u4f9bu8005
final loginMethodProvider = StateProvider.autoDispose<LoginMethod>((ref) {
  return LoginMethod.phone; // u9ed8u8ba4u4f7fu7528u624bu673au9a8cu8bc1u7801u767bu5f55
});

/// u767bu5f55u65b9u5f0fu679au4e3e
enum LoginMethod {
  /// u624bu673au9a8cu8bc1u7801u767bu5f55
  phone,
  
  /// u8d26u53f7u5bc6u7801u767bu5f55
  password,
}

/// u8eabu4efdu9a8cu8bc1u72b6u6001u7ba1u7406u5668
class AuthNotifier extends StateNotifier<AuthState> {
  final AuthService _authService;

  AuthNotifier(this._authService) : super(const AuthState.loading()) {
    _initialize();
  }

  /// u521du59cbu5316 - u68c0u67e5u662fu5426u5df2u767bu5f55
  Future<void> _initialize() async {
    final currentUser = _authService.getCurrentUser();
    if (currentUser != null) {
      state = AuthState.authenticated(currentUser);
    } else {
      state = const AuthState.unauthenticated();
    }
  }

  /// u53d1u9001u9a8cu8bc1u7801
  Future<bool> sendVerificationCode(String phone) async {
    return await _authService.sendVerificationCode(phone);
  }

  /// u624bu673au53f7u9a8cu8bc1u7801u767bu5f55
  Future<bool> loginWithPhone(String phone, String code) async {
    state = const AuthState.loading();
    final user = await _authService.loginWithPhone(phone, code);
    if (user != null) {
      state = AuthState.authenticated(user);
      return true;
    } else {
      state = const AuthState.unauthenticated();
      return false;
    }
  }
  
  /// u8d26u53f7u5bc6u7801u767bu5f55
  Future<bool> loginWithPassword(String username, String password) async {
    state = const AuthState.loading();
    final user = await _authService.loginWithPassword(username, password);
    if (user != null) {
      state = AuthState.authenticated(user);
      return true;
    } else {
      state = const AuthState.unauthenticated();
      return false;
    }
  }
  
  /// u9a8cu8bc1u6ed1u5757u9a8cu8bc1u7801
  Future<bool> verifyCaptcha(String token) async {
    return await _authService.verifyCaptcha(token);
  }

  /// u5faeu4fe1u767bu5f55
  Future<bool> loginWithWeChat() async {
    state = const AuthState.loading();
    final user = await _authService.loginWithWeChat();
    if (user != null) {
      state = AuthState.authenticated(user);
      return true;
    } else {
      state = const AuthState.unauthenticated();
      return false;
    }
  }

  /// u9000u51fau767bu5f55
  Future<void> logout() async {
    state = const AuthState.loading();
    final result = await _authService.logout();
    if (result) {
      state = const AuthState.unauthenticated();
    } else {
      // u6062u590du4e4bu524du7684u72b6u6001
      _initialize();
    }
  }
}

/// u8eabu4efdu9a8cu8bc1u72b6u6001
class AuthState {
  final bool isLoading;
  final bool isAuthenticated;
  final UserModel? user;

  const AuthState({
    required this.isLoading,
    required this.isAuthenticated,
    this.user,
  });

  /// u52a0u8f7du4e2du72b6u6001
  const AuthState.loading()
      : isLoading = true,
        isAuthenticated = false,
        user = null;

  /// u5df2u8ba4u8bc1u72b6u6001
  const AuthState.authenticated(UserModel this.user)
      : isLoading = false,
        isAuthenticated = true;

  /// u672au8ba4u8bc1u72b6u6001
  const AuthState.unauthenticated()
      : isLoading = false,
        isAuthenticated = false,
        user = null;
}

/// u9a8cu8bc1u7801u53d1u9001u72b6u6001
class SendCodeState {
  final bool isSending;
  final bool isSent;
  final int? countdown;
  final String? error;

  const SendCodeState({
    required this.isSending,
    required this.isSent,
    this.countdown,
    this.error,
  });

  /// u521du59cbu72b6u6001
  const SendCodeState.initial()
      : isSending = false,
        isSent = false,
        countdown = null,
        error = null;

  /// u53d1u9001u4e2du72b6u6001
  const SendCodeState.sending()
      : isSending = true,
        isSent = false,
        countdown = null,
        error = null;

  /// u5df2u53d1u9001u72b6u6001
  const SendCodeState.sent(int this.countdown)
      : isSending = false,
        isSent = true,
        error = null;

  /// u9519u8befu72b6u6001
  const SendCodeState.error(String this.error)
      : isSending = false,
        isSent = false,
        countdown = null;

  /// u521bu5efau65b0u72b6u6001
  SendCodeState copyWith({
    bool? isSending,
    bool? isSent,
    int? countdown,
    String? error,
  }) {
    return SendCodeState(
      isSending: isSending ?? this.isSending,
      isSent: isSent ?? this.isSent,
      countdown: countdown ?? this.countdown,
      error: error ?? this.error,
    );
  }
}

/// u6ed1u5757u9a8cu8bc1u7801u72b6u6001
class CaptchaState {
  final bool isVerifying;
  final bool isVerified;
  final String? token;
  final String? error;

  const CaptchaState({
    required this.isVerifying,
    required this.isVerified,
    this.token,
    this.error,
  });

  /// u521du59cbu72b6u6001
  const CaptchaState.initial()
      : isVerifying = false,
        isVerified = false,
        token = null,
        error = null;

  /// u9a8cu8bc1u4e2du72b6u6001
  const CaptchaState.verifying()
      : isVerifying = true,
        isVerified = false,
        token = null,
        error = null;

  /// u5df2u9a8cu8bc1u72b6u6001
  const CaptchaState.verified(String this.token)
      : isVerifying = false,
        isVerified = true,
        error = null;

  /// u9519u8befu72b6u6001
  const CaptchaState.error(String this.error)
      : isVerifying = false,
        isVerified = false,
        token = null;

  /// u521bu5efau65b0u72b6u6001
  CaptchaState copyWith({
    bool? isVerifying,
    bool? isVerified,
    String? token,
    String? error,
  }) {
    return CaptchaState(
      isVerifying: isVerifying ?? this.isVerifying,
      isVerified: isVerified ?? this.isVerified,
      token: token ?? this.token,
      error: error ?? this.error,
    );
  }
}
